package com.coffee.service.impl;

import com.coffee.constant.MessageConstant;
import com.coffee.constant.StatusConstant;
import com.coffee.dto.DishDTO;
import com.coffee.dto.DishPageQueryDTO;
import com.coffee.entity.Dish;
import com.coffee.entity.DishFlavor;
import com.coffee.entity.Setmeal;
import com.coffee.exception.DeletionNotAllowedException;
import com.coffee.mapper.DishFlavorMapper;
import com.coffee.mapper.DishMapper;
import com.coffee.mapper.SetmealDishMapper;
import com.coffee.mapper.SetmealMapper;
import com.coffee.result.PageResult;
import com.coffee.service.DishService;
import com.coffee.vo.DishVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    /**
     * 新增菜品
     * @param dishDTO
     */
    //涉及到多个表，加注解保证一致性
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
//        菜品表插入1条数据
        dishMapper.insert(dish);
        //获取insert语句获得的主键值
        Long dishId=dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null&&flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            // 口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);
        long total=page.getTotal();
        List<DishVO> records=page.getResult();
        return new PageResult(total,records);
    }

    /**
     * 菜品 批量删除
     * @param ids
     */
    @Transactional
    public void delete(List<Long> ids) {
//        判断当前菜品是否能够删除。业务规则：可以一次删除一个菜品，也可以批量删除；起售中的菜品不能删除；被套餐关联的菜品不能删除；删除菜品之后关联的口味也要删除。

        for (Long id:ids) {
            Dish dish=dishMapper.getById(id);
            //1.是否有起售中的
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //2.是否有套餐关联
        List<Long> setmealIdsByDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIdsByDishIds!=null&&setmealIdsByDishIds.size()>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的数据
//        for(Long id:ids){
//            dishMapper.deleteById(id);
//            //3.关联口味
//            dishFlavorMapper.deleteByDishId(id);
//        }
        //根据菜品集合批量删除菜品表信息以及关联的口味信息
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);



    }

    /**
     * 根据id查询菜品信息以及对应的口味
     * @param id
     * @return
     */
    public DishVO getById(Long id) {

        Dish dish = dishMapper.getById(id);
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setCategoryName(dishMapper.getCategoryNameById(dish.getCategoryId()));
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改菜品信息和对应的口味信息
     * @param dishDTO
     */
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //菜品表修改
        dishMapper.update(dish);
        //口味表修改：先删除再插入
        dishFlavorMapper.deleteByDishId(dish.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null&&flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            //要保证不为空才能插入
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品起售停售
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        Dish dish=new Dish();
        dish.setId(id);
        dish.setStatus(status);
        //如果status=停售
        if(status==StatusConstant.DISABLE){
            //判断是否有关联套餐在起售状态
            List<Long> setmealIds=setmealDishMapper.getSetmealIdsByDishId(id);
            if (setmealIds!=null&&setmealIds.size()>0){
                //将关联套餐改为停售状态
                setmealIds.forEach(setmealId->{
                    Setmeal setmeal=new Setmeal();
                    setmeal.setId(setmealId);
                    setmealMapper.update(setmeal);
                });
            }
        }
        dishMapper.update(dish);
    }



    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);
        
        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
